package liang.jiaxin.com.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import liang.jiaxin.com.domain.Bbs;
import liang.jiaxin.com.domain.ResourceInfo;
import liang.jiaxin.com.dto.Contain;
import liang.jiaxin.com.dto.request.bbs.BbsRequestDTO;
import liang.jiaxin.com.dto.response.bbs.BbsResponseDTO;
import liang.jiaxin.com.mapper.BbsMapper;

import liang.jiaxin.com.mapper.ResourceInfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Jrxsr
 * @since 2019-04-13
 */
@Service
public class BbsService extends ServiceImpl<BbsMapper, Bbs>{
    @Autowired
    BbsMapper bbsMapper;
    @Autowired
    ResourceInfoMapper resourceInfoMapper;

    public int insert(BbsRequestDTO requestDTO) {

        String imageurl = requestDTO.getImageurl();
        Integer resourceId = null;
        if (StringUtils.isEmpty(imageurl)) {
            ResourceInfo resourceInfo = new ResourceInfo();
            resourceInfo.setCreateDatetime(new Date());
            resourceInfo.setUpdateDatetime(new Date());
            resourceInfo.setUrl(imageurl);
            resourceInfo.setType(Contain.ResourceType.TYPE_IMAGE);
            resourceInfoMapper.insert(resourceInfo);
            resourceId = resourceInfo.getId();
        }

        Bbs bbs = new Bbs();
        BeanUtils.copyProperties(requestDTO, bbs);
        if (!Objects.isNull(resourceId)) {
            bbs.setResourceId(resourceId.toString());
        }
        return bbsMapper.insert(bbs);
    }

    public List<BbsResponseDTO> queryList() {
        List<Bbs> bbs = bbsMapper.selectList(new QueryWrapper<Bbs>().orderByDesc(Bbs.CREATEDATETIME));
        List<BbsResponseDTO> responseDTOList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(bbs)) {
            for (Bbs bb : bbs) {
                BbsResponseDTO bbsResponseDTO = new BbsResponseDTO();
                BeanUtils.copyProperties(bb, bbsResponseDTO);
//                ResourceInfo resourceInfo = resourceInfoMapper.selectResourceById(Integer.valueOf(bb.getResourceId()));
                if (bb != null) {
                    ResourceInfo resourceInfo = resourceInfoMapper.selectById(Integer.valueOf(bb.getResourceId()));
                    if (resourceInfo!=null) {
                        bbsResponseDTO.setImageurl(resourceInfo.getUrl());
                    }
                }
                responseDTOList.add(bbsResponseDTO);
            }
        }
        return responseDTOList;
    }
}